<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="util.ServletHelp"%>
<%@page import="global.Constants"%>
<html>
<head>
	<%
		String baseUrl = request.getContextPath();
	%>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<script type="text/javascript">
	    //这里的全局是为了修改之后的刷新
	    var userListGrid;
		var editUserWindow;
		$(document).ready(function(){
		    //角色勾选的变量
		    var checkid;
		    var checktext;
		    //部门的变量
		    var deptid;
		    var depttext;
			// 全局参数
			var baseParams = {limit:<%=Constants.PAGE_SIZE %>,start : 0};
			var EXT_QUERY_TIME_OUT = 1200000;

			// 用户数据源
		    var userListStore = new Ext.data.JsonStore({
		        url: '${pageContext.request.contextPath}/returnUserInforPagesize.action',
		        root: 'datas',
				timeout : EXT_QUERY_TIME_OUT,
		        totalProperty: 'results',
		        fields: ['id', 'name', 'role_name', 'dept_name', 'Login_name', 'mobile', 'email'],
		        baseParams: baseParams,
		        autoLoad: true,
				listeners : {  
          load : function() {  
              isDetailReady = true;// 查询置换标志为已查过   
            }  
            }  
		    });
			
		   	    // 工具栏
		    var userListToolbar = new Ext.Toolbar({
		    	renderTo: 'userListToolBarDiv',
		    	items: [
					new Ext.Button({
					    id: 'userList-add-button',
					    text: '添加',
						iconCls: 'user_add'
						//disabled:true
					}),
					new Ext.Button({
					    id: 'userList-update-button',
					    text: '编辑用户',
						iconCls: 'user_edit'
					}),
					new Ext.Button({
					    id: 'userList-delete-button',
					    text: '删除',
						iconCls: 'status_busy'
					}),
					'-',
		            new Ext.ux.form.SearchField({
		                store: userListStore,
		                width: 320,
		                paramName: 'name',
		                emptyText: '请输入用户姓名...',
		                style: 'margin-left: 10px;'
		            })
				]
			});

			// 用户数据表格
			var sm = new Ext.grid.CheckboxSelectionModel();
			userListGrid = new Ext.grid.GridPanel({
				id: 'userListGrid',
				renderTo: 'userListGridDiv',
				border: false,
				stateful: true,
			    autoScroll: 'auto',
		        store: userListStore,
		        loadMask: true,
		        cm: new Ext.grid.ColumnModel({
		            defaults: {
		                width: 100,
		                sortable: true
		            },
			        columns: [
						sm,
						new Ext.grid.RowNumberer({header:'№',width:50}),
						{id:'id',header: '用户ID', width: 100, hidden: true, sortable: true, dataIndex: 'id'},
			            {id:'name',header: '用户姓名', width: 100, sortable: true, dataIndex: 'name'},
			            {id:'role_name',header: '角色', width: 200, sortable: true, dataIndex: 'role_name'},
			            {id:'dept_name',header: '部门', width: 100, sortable: true, dataIndex: 'dept_name'},
			            {id:'Login_name',header: '登录账号', width: 100, sortable: true, dataIndex: 'Login_name'},
			            {id:'mobile',header: '用户手机号', width: 100, sortable: true, dataIndex: 'mobile'},
			            {id:'email',header: '用户Email', width: 180, sortable: true, dataIndex: 'email'}
					]
		        }),
		        sm: sm,
		        columnLines: true,
		        bbar: new Ext.PagingToolbar({
					pageSize: <%=Constants.PAGE_SIZE %>,
					store: userListStore,
					displayInfo: true,
					displayMsg: Anynote.PAGINGTOOLBAR_DISPLAYMSG,
					emptyMsg: Anynote.PAGINGTOOLBAR_EMPTYMSG,
					doLoad: function(start){
						baseParams.start = start;
						this.store.load({params: baseParams});
					}
		        })
		    });
			// 设置Grid高度和宽度
			Anynote.resizeGridTo("userListGrid", 0, 56);
			
			// 添加按钮
			$("#userList-add-button").click(function(){
		     	// 性别数据源
		        var sexStore = new Ext.data.ArrayStore({  
		            fields : ['sex', 'sexName'],  
		            data : <%=ServletHelp.getArrayFromMap(Constants.SEX_MAP, null)%>,
		            sortInfo: {field: "sex", direction: "ASC"}
		        });

		     	// 风格数据源
		        var themeStore = new Ext.data.SimpleStore({  
		            fields : ['theme', 'themeName'],  
		            data : Anynote.THEME_DATA  
		        });
		        
		   //给用户添加角色    
		   var comboWithTooltipRole = new Ext.form.ComboBox({
		    fieldLabel: '角色',
            store:new Ext.data.SimpleStore({fields:[],data:[[]]}),  
            editable:false,  
            mode: 'local',  
            triggerAction:'all',  
            maxHeight: 200,  
			allowBlank:false,
            tpl: '<div style="height:200px"><div id="treeRole"></div></div>',  
            onSelect:Ext.emptyFn,
            emptyText:'请选择...',
            anchor:'98%',
            // applyTo: 'comboxtreeRole'
            renderTo: Ext.getBody()    
        });
        
        comboWithTooltipRole.render('comboWithTooltipRole');  
        
        var treeRole = new Ext.tree.TreePanel({  
                border:false,  
                autoScroll:true,
                animate:true,
                autoWidth:true,
                autoHeight:true,
                enableDD:true,
                containerScroll: true, 
                loader: new Ext.tree.TreeLoader({
                    dataUrl:'${pageContext.request.contextPath}/newRole.action',
                    listeners : {
					beforeload : function(treeLoader, node) {
						this.baseParams.parentId = node.id
						this.baseParams.text = node.text
						this.baseParams.leaf = node.leaf
					}
				}           
                })
            });

        var rootRole = new Ext.tree.AsyncTreeNode({
                id:'-1',                      //节点id
                text: '角色',                  //节点名称
                draggable:true,                  //是否支持拖动
                nodeType: 'async', 
                leaf:false,
                checked : false
        });
          
            treeRole.setRootNode(rootRole);
            comboWithTooltipRole.on('expand',function(){  
            treeRole.render('treeRole');  
            //加载所有的子节点
            //tree.expandAll(); 
            });  
            
        
        treeRole.on('checkchange', function(node, checked) {
                        node.expand();
                        node.attributes.checked = checked;
                        node.eachChild(function(child) {
                                    child.ui.toggleCheck(checked);
                                    child.attributes.checked = checked;
                                    child.fireEvent('checkchange', child,
                                            checked);
                               });
                            //这里是遍历勾选的角色
                            var b = treeRole.getChecked();
                            checkid = new Array;// 存放选中id的数组
                            checktext = new Array;// 存放选中text的数组
                            for (var i = 0; i < b.length; i++) {
                                checktext.push(b[i].text);// 添加text到数组
                                checkid.push(b[i].id);// 添加id到数组
                                
                            }
                       comboWithTooltipRole.setValue(checktext.toString());
                    }, treeRole);
            
            //给用户添加部门
            var comboWithTooltipDept = new Ext.form.ComboBox({
			    fieldLabel: '部门',
	            store:new Ext.data.SimpleStore({fields:[],data:[[]]}),  
	            editable:false,  
	            mode: 'local',  
	            triggerAction:'all',  
	            maxHeight: 200,  
				allowBlank:false,
	            tpl: '<div style="height:200px"><div id="treeDept"></div></div>',  
	            onSelect:Ext.emptyFn,
	            emptyText:'请选择...',
	            anchor:'98%',
	            // applyTo: 'comboxtreeDept'  
	            renderTo: Ext.getBody()
           });
        
        comboWithTooltipDept.render('comboWithTooltipDept');  
        
        var treeDept = new Ext.tree.TreePanel({  
                border:false,  
                autoScroll:true,
                animate:true,
                autoWidth:true,
                autoHeight:true,
                enableDD:true,
                containerScroll: true, 
                loader: new Ext.tree.TreeLoader({
                    dataUrl:'${pageContext.request.contextPath}/department_getDepartmentTree.action',
                    listeners : {
					beforeload : function(treeLoader, node) {
						this.baseParams.parentId = node.id
						this.baseParams.text = node.text
						this.baseParams.leaf = node.leaf
					}
				}           
                })
            });
            
        var rootDept = new Ext.tree.AsyncTreeNode({
                id:'-1',                      //节点id
                text: '部门',                  //节点名称
                draggable:true,                  //是否支持拖动
                nodeType: 'async', 
                leaf:false
        });
          
            treeDept.setRootNode(rootDept);
            comboWithTooltipDept.on('expand',function(){  
            treeDept.render('treeDept');  
            //加载所有的子节点
            //tree.expandAll(); 
            });  
            
            
            treeDept.on("click",function(node,event)
        {
            deptid = node.id;// 添加id到数组
            depttext = node.text;// 添加text到数组
            comboWithTooltipDept.setValue(depttext); 
            var form = addUserFormPanel.getForm();
            form.findField('deptname').setValue(depttext);
            comboWithTooltipDept.collapse();  
        });
        
				// 新增用户Form
				var addUserFormPanel = new Ext.FormPanel({
					id: 'addUserFormPanel',
			        labelWidth: 60,
			        buttonAlign: 'center',
			        border: false,
			        bodyStyle: 'padding:10px;text-align:left;background-color:transparent;',
			        url: '',
		            items:[{// 账号
			                xtype:'textfield',
			                name: 'userId',
			                fieldLabel: '账号',
			                blankText:'账号不能为空',
			                anchor:'98%',
			                allowBlank:false,
			                maxLength: 20,
			                listeners:{
			                blur:function(n){
			                var va = n.getValue();
			                Ext.Ajax.request({
	                        url:  '${pageContext.request.contextPath}/proving_provingOnly.action',
		                    params:{val:va,filed:'Login_name',table:'t_u_user_Info'},
		                    success: function(res){
		                      var isPorv = res.responseText;
		                      if(isPorv == 1){
		                        n.setValue('');
		                        Ext.Msg.alert('错误', '该登录名已经存在,请重新输入!!!');
		                        }
			                }
			                })
			                }
			                }
			           },new Ext.form.TextField ({// 密码
			        	   inputType: 'password',
			               name:'password',
			               fieldLabel:'密码',
			               anchor:'98%',
			               allowBlank:false,
			               maxLength: 20
			           }),new Ext.form.TextField ({// 确认密码
		            	   inputType: 'password',
			               name:'repassword',
			               fieldLabel:'确认密码',
			               anchor:'98%',
			               allowBlank:false,
			               maxLength: 20
		                }),{// 隐藏勾选角色名的值
			               xtype:'hidden',
			               id:'rolename',
			               name: 'rolename'
			           },{// 隐藏点击部门名的值
			               xtype:'hidden',
			               id:'deptname',
			               name: 'deptname'
			           },comboWithTooltipRole
		                ,comboWithTooltipDept
		                ,{// 姓名
			               xtype:'textfield',
			               id:'userName',
			               name:'userName',
			               fieldLabel:'姓名',
			               anchor:'98%',
			               allowBlank:false,
			               maxLength: 20
			           },{// 性别
			                xtype:'combo',
			                hiddenName: 'sex',
			                fieldLabel: '性别',
			                store: sexStore,
			                mode : 'local',
			                triggerAction: "all",
			                valueField: 'sex',
			                displayField: 'sexName',
			                allowBlank:false,
			                editable: false,
			                width: 230,
			                anchor:'98%'
		                },{// 生日
			                xtype:'datefield',
			                name: 'birthdayStr',
			                fieldLabel: '生日',
			                format: 'Y-m-d',
			                width: 230,
			                anchor:'98%'
		                },{// 邮箱
			               xtype:'textfield',
			               name:'email',
			               fieldLabel:'邮箱',
			               anchor:'98%',
			               vtype:'email',
			               allowBlank:false,
			               maxLength: 50
			           },{// 电话
			               xtype:'numberfield',
			               name:'phone',
			               fieldLabel:'电话',
			               anchor:'98%',
			               maxLength: 20
			           }],
			        buttons: [{
	                    text:'提交',
	                    handler: function(){
				        	var form = addUserFormPanel.getForm();
						    if(form.isValid()){
						        form.findField('rolename').setValue(checktext.toString());
						    	// 发送请求
								Anynote.ajaxRequest({
									baseUrl: '<%=baseUrl %>',
									baseParams: form.getValues(),
									action: '${pageContext.request.contextPath}/registerUserInfor.action?checkid='+checkid.toString()+'&deptid='+deptid,
									callback: function(jsonResult){
										userListGrid.getStore().reload();
										addUserWindow.close();
									},
									showWaiting: true,
									failureMsg: '保存失败.'
								});
							}
	                	}
	                },{
	                    text: '重置',
	                    handler: function(){
	                		addUserFormPanel.getForm().reset();
	                    }
	                }]
			    });
				// 用户注册窗口
				var addUserWindow = new Ext.Window({
					title: '添加用户',
					width: 330,
					height: 350,
					modal: true,
					maximizable: false,
					resizable: false,
					iconCls: 'user_add',
					layout:'fit',
					plain: true,
					items: [addUserFormPanel]
				}).show();
			});

			// 启用编辑用户
			$("#userList-update-button").click(function(){
				// 启用
				submit("update");
			});

			// 删除按钮
			$("#userList-delete-button").click(function(){
				// 提交
				submit("delete");
			});

			// 提交
			function submit(type){
				var msg = "";
				var status = 0;
				if(type=="delete"){
				    status = 1;
					msg = "确定要删除该用户吗？";
				}else if(type=="update"){
				    status = 2;
				}
				var records = userListGrid.getSelectionModel().getSelections();
				
				if(records.length < 1){
					 Ext.Msg.alert("提示", "请至少选择一条数据.");
				}else{
					   //如果点击的是删除用户
					   if(status == 1){
					      Ext.Msg.confirm("警告", msg, function(btn){
						  if(btn=="yes"){
							var userIds = "";
							for(var i=0;i<records.length;i++){
								userIds = userIds + records[i].get("id") + ",";
							}
							// 发送请求
							Anynote.ajaxRequest({
								baseUrl: '<%=baseUrl %>',
								baseParams: {userIds:userIds, status:status},
								action: '${pageContext.request.contextPath}/deleteUserInfor.action',
								callback: function(jsonResult){
									userListGrid.getStore().reload();
								},
								showWaiting: true,
								failureMsg: '保存失败.'
							});
						   }
					     });
					   //如果点击的是编辑用户
					   }else if(status == 2){
					        var userIds = "";
						    userIds = records[0].get("id");
					        //只能一条一条的编辑，不能多个一起编辑
					        if(records.length == 1){
						        editUserWindow = new Ext.Window({
								title: '编辑用户',
								width: 330,
								height: 290,
								modal: true,
			
								maximizable: false,
								resizable: false,
								layout:'fit',
								iconCls: 'user_edit',
								plain: true,
								autoLoad:{url:'${pageContext.request.contextPath}/page/user/editUser.jsp?userId='+userIds,scripts:true,nocache:true},
								listeners: {
									close: function(){
										//var buttonType = Ext.getCmp("buttonType").getValue();
										
										//Anynote.reloadTreeNode(Ext.getCmp("treeRole_edit"), null, null);
										// Ext.getCmp('treeRole_edit');
										if(Ext.getCmp('cr') != null){Ext.getCmp('cr').destroy()};//把它destroy就可以了}
										if(Ext.getCmp('cd') != null){Ext.getCmp('cd').destroy()};//把它destroy就可以了}
									}
								}
								});
								editUserWindow.show();
					        }else{
					            Ext.Msg.alert("提示", "只能选择一条数据.");
					        }
					   }
					}
			}
});

	</script>
</head>
<body>
<div id="userListDiv">
	<div id="userListToolBarDiv"></div>
	<div id="userListGridDiv" style="width:100%;height:100%;"></div>
</div>
<%-- 
<div id="textDiv" style="display:none">
<input type="text" name="comboxtreeRole" id="comboxtreeRole">
<input type="text" name="comboxtreeDept" id="comboxtreeDept">
</div>
--%>
</body>
</html>
